import random
from functools import wraps

from flask import Blueprint, views, render_template, request, flash, redirect, url_for, session, g
from flask_mail import Message

from apps import mail
from .forms import *
from .models import *
from apps.utils import resful
import config, string

bp = Blueprint('cms', __name__, url_prefix='/cms')


# 登录装饰器
def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if config.CMS_USER_ID not in session:
            return redirect(url_for('cms.login'))
        return func(*args, **kwargs)

    return wrapper


# 访问权限装饰器
def permission_required(permission):
    def permission_wrapper(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if not g.cms_user.has_permission(permission):
                return redirect(url_for('cms.index'))
            return func(*args, **kwargs)

        return wrapper

    return permission_wrapper


@bp.route('/')
@login_required
def index():
    return render_template('cms/cms_index.html')


class LoginView(views.MethodView):
    def get(self, email=None):
        return render_template('cms/cms_login.html', email=email)

    def post(self):
        form = LoginForm(request.form)
        if form.validate():
            email = form.data['email']
            password = form.data['password']
            remember = form.data['remember']
            user = CMSUser.query.filter_by(email=email).first()
            if not user:
                flash('用户名或者密码错误', 'err')
                return redirect(url_for('cms.login', email=email))
            if user.check_password(password) == False:
                flash('用户名或者密码错误', 'err')
                return redirect(url_for('cms.login', email=email))
            if remember:
                session.permanent = True  # 设置session的过期时间
            session[config.CMS_USER_ID] = user.id
            return redirect(url_for('cms.index'))
        flash(form.get_error(), 'err')
        return redirect(url_for('cms.login'))


bp.add_url_rule('/login/', view_func=LoginView.as_view('login'))


@bp.route('/logout')
def logout():
    session.pop(config.CMS_USER_ID)
    return redirect(url_for('cms.login'))


@bp.route('/profile/')
@login_required
@permission_required(CMSPermission.VISITER)
def profile():
    return render_template('cms/cms_profile.html')


@bp.route('/resetpwd/', methods=['GET', 'POST'])
@login_required
@permission_required(CMSPermission.VISITER)
def resetpwd():
    if request.method == 'POST':
        form = ResetpwdForm(request.form)
        if not form.validate():
            return resful.param_error(message=form.get_error())
        oldpwd = form.old_pwd.data
        newpwd1 = form.new_pwd1.data
        user = g.cms_user
        if not user.check_password(oldpwd):
            return resful.param_error(message='请输入正确的旧密码')
        user.password = newpwd1
        db.session.commit()
        return resful.success(message='修改成功')
    return render_template('cms/cms_resetpwd.html')


@bp.route('/resetemail/', methods=['GET', 'POST'])
@login_required
@permission_required(CMSPermission.VISITER)
def resetemail():
    form = ResetEmailForm(request.form)
    return render_template('cms/cms_resetemail.html')


@bp.route('/sendCaptcha/')
@login_required
@permission_required(CMSPermission.VISITER)
def send_captcha():
    old_email = request.args.get('email', None)
    print(old_email)
    user = g.cms_user
    if user.email != old_email:
        return resful.param_error('请输入正确的旧邮箱')
    str_list = list(string.ascii_letters)
    str_list.extend(['2', '3', '4', '5', '6', '7', '8', '9'])
    captcha = ''.join(random.sample(str_list, 6))
    print(captcha)
    message = Message('june论坛邮箱验证', recipients=[old_email], body='您的邮箱验证码为: %s' % captcha)

    mail.send(message)

    return resful.success('验证码发送成功')


@bp.route('/post_list/')
@login_required
@permission_required(CMSPermission.POSTER)
def post_list():
    """帖子列表"""
    posts = CMSArticle.query.order_by(CMSArticle.add_time.desc()).all()
    return render_template('cms/poster_list.html', posts=posts)


@bp.route('/add_high/', methods=['POST'])
@login_required
@permission_required(CMSPermission.POSTER)
def add_high():
    form = AddHighLight(request.form)
    if form.validate():
        article_id = form.post_id.data
        article = CMSArticle.query.get_or_404(article_id)
        if article.highlight:
            light = HighLightArticlr.query.filter_by(article_id=article_id).first()
            db.session.delete(light)
        else:
            light = HighLightArticlr(article_id=article_id)
            db.session.add(light)
        db.session.commit()
        return resful.success()
    else:
        return resful.param_error(form.get_error())

@bp.route('/delete_article/', methods=['POST'])
@login_required
@permission_required(CMSPermission.POSTER)
def delete_article():
    form = DeleteArticle(request.form)
    if form.validate():
        article_id = form.post_id.data
        article = CMSArticle.query.get_or_404(article_id)
        if not article:
            return resful.param_error(message='你要删除的帖子不存在')
        # 删除帖子的同时删除加精表的内容
        highlight = HighLightArticlr.query.filter_by(article_id=article_id).first()
        if highlight:
            db.session.delete(highlight)
        db.session.delete(article)
        db.session.commit()
        return resful.success()
    else:
        return resful.param_error(form.get_error())


@bp.route('/un_high/')
@login_required
@permission_required(CMSPermission.POSTER)
def un_high():
    pass


@bp.route('/comment_list/')
@login_required
@permission_required(CMSPermission.COMMENTER)
def comment_list():
    return render_template('cms/comment_list.html')


@bp.route('/board_list/')
@login_required
@permission_required(CMSPermission.BOARDER)
def board_list():
    boards = CMSBoard.query.all()
    return render_template('cms/cms_board_list.html', boards=boards)


@bp.route('/add_board/', methods=['POST'])
@login_required
@permission_required(CMSPermission.BOARDER)
def add_board():
    form = BorderForm(request.form)
    if form.validate():
        board_name = form.board_name.data
        board = CMSBoard.query.filter_by(board_name=board_name).first()
        if board:
            return resful.param_error(message="您输入的板块名称已经存在,请重新输入")
        new_board = CMSBoard(board_name=board_name)
        db.session.add(new_board)
        db.session.commit()
        return resful.success()
    else:
        return resful.param_error(form.get_error())


@bp.route('/edit_board/', methods=['POST'])
@login_required
@permission_required(CMSPermission.BOARDER)
def edit_board():
    form = EditBoard(request.form)
    if form.validate():
        board_id = form.board_id.data
        board = CMSBoard.query.filter_by(id=int(board_id)).first()
        if not board:
            return resful.param_error(message='板块不存在')
        board.board_name = form.board_name.data
        db.session.commit()
        return resful.success()
    else:
        return resful.param_error(form.get_error())


@bp.route('/delete_board/', methods=['POST'])
@login_required
@permission_required(CMSPermission.BOARDER)
def delete_board():
    form = DeleteBoard(request.form)
    if form.validate():
        board_id = form.board_id.data
        board = CMSBoard.query.filter_by(id=int(board_id)).first()
        if not board:
            return resful.param_error(message='板块不存在')
        db.session.delete(board)
        db.session.commit()
        return resful.success()
    else:
        return resful.param_error(form.get_error())


@bp.route('/front_user/')
@login_required
@permission_required(CMSPermission.FRONTUSER)
def front_user():
    return render_template('cms/front_user.html')


@bp.route('/cms_user/')
@login_required
@permission_required(CMSPermission.CMSUSER)
def cms_user():
    return render_template('cms/cms_user.html')


@bp.route('/banners/')
@login_required
def banner_list():
    banners = CMSBanner.query.order_by(CMSBanner.priority.desc()).all()
    return render_template('cms/cms_banner_list.html', banners=banners)


@bp.route('/add_banner/', methods=['POST'])
@login_required
def add_banner():
    form = BannerFrom(request.form)
    if form.validate():
        img_name = form.img_name.data
        img_url = form.img_url.data
        link_url = form.link_url.data
        priority = form.priority.data
        banner = CMSBanner(img_name=img_name, img_url=img_url, link_url=link_url, priority=priority)
        db.session.add(banner)
        db.session.commit()
        return resful.success()
    else:
        return resful.param_error(form.get_error())


@bp.route('/edit_banner/', methods=['POST'])
@login_required
def edit_banner():
    form = EditBannerForm(request.form)
    if form.validate():
        banner_id = form.banner_id.data
        banner = CMSBanner.query.filter_by(id=int(banner_id)).first()
        if not banner:
            return resful.param_error(message="轮播图ID不存在")
        banner.img_name = form.img_name.data
        banner.img_url = form.img_url.data
        banner.link_url = form.link_url.data
        banner.priority = form.priority.data
        db.session.commit()
        return resful.success()
    else:
        return resful.param_error(form.get_error())


@bp.route('/delete_banner/', methods=['POST'])
@login_required
def delete_banner():
    form = DeleteBanner(request.form)
    if form.validate():
        banner_id = form.banner_id.data
        banner = CMSBanner.query.filter_by(id=int(banner_id)).first()
        if not banner:
            return resful.param_error(message="轮播图ID不存在")
        db.session.delete(banner)
        db.session.commit()
        return resful.success()
    else:
        return resful.param_error(form.get_error())
